<template>
	<div ref="echartsRef" class="echarts-container"></div>
</template>
<script setup name="ECharts">
import * as echarts from "echarts";

const emit = defineEmits(["legendChange", "sendMyChart"]);

const props = defineProps({
	option: {
		type: Object,
		default: () => {
			return {};
		}
	}
});

const echartsRef = ref(null);
let echartsInstance = null;

watch(
	() => props.option,
	() => {
		init();
	},
	{ deep: true }
);

const init = () => {
	echartsInstance.clear();
	echartsInstance.setOption(props.option);
	window.addEventListener("resize", () => {
		echartsInstance.resize();
	});
};

onMounted(() => {
	nextTick(() => {
		echartsInstance = echarts.init(echartsRef.value);
		init();
		emit("sendMyChart", echartsInstance);
	});
});

function legendChange() {
	if (!echartsInstance) return;
	echartsInstance.on("legendselectchanged", function (params) {
		// 获取所有被选中的图例名称
		let selectedLegends = [];
		for (let legendName in params.selected) {
			if (params.selected[legendName]) {
				selectedLegends.push(legendName);
			}
		}

		// console.log("Currently selected legends:", selectedLegends);
		emit("legendChange", selectedLegends);
	});
}

setTimeout(() => {
	legendChange();
}, 3000);
</script>
<style lang="scss" scoped>
.echarts-container {
	width: 100%;
	height: 100%;
	margin: 0 auto;
}
</style>
